package com.example.newhabitclock.TimeAdd

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.newhabitclock.R
import com.example.newhabitclock.databinding.FragmentClockTwoBinding

class ClockTwoFragment : Fragment() {
    // ViewModel scoped to activity for persistence across fragment switches
    private val viewModel: StopwatchViewModel by activityViewModels()
    private var _binding: FragmentClockTwoBinding? = null
    private val binding get() = _binding!!

    // Handler for updating time every 10ms
    private val handler = Handler(Looper.getMainLooper())
    private val updateTimeRunnable = object : Runnable {
        override fun run() {
            val displayTime = viewModel.getCurrentDisplayTime()
            binding.timeTextView.text = formatTime(displayTime)
            handler.postDelayed(this, 10)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentClockTwoBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // Set up RecyclerView for marks
        val adapter = MarkAdapter()
        binding.marksRecyclerView.apply {
            this.adapter = adapter
            layoutManager = LinearLayoutManager(
                context,
                LinearLayoutManager.VERTICAL,
                false
            )
        }

        // Observe state changes to update UI
        viewModel.stateLiveData.observe(viewLifecycleOwner) { state ->
            when (state) {
                StopwatchState.STOPPED -> {
                    binding.buttonLeft.visibility = View.GONE
                    binding.buttonRight.text = "开始"
                    binding.buttonRight.setOnClickListener { viewModel.start() }
                    handler.removeCallbacks(updateTimeRunnable)
                    binding.timeTextView.text = "00:00.00"
                }

                StopwatchState.RUNNING -> {
                    binding.buttonLeft.visibility = View.VISIBLE
                    binding.buttonLeft.text = "标记"
                    binding.buttonLeft.setOnClickListener { viewModel.addMark() }
                    binding.buttonRight.text = "暂停"
                    binding.buttonRight.setOnClickListener { viewModel.pause() }
                    handler.post(updateTimeRunnable)
                }

                StopwatchState.PAUSED -> {
                    binding.buttonLeft.visibility = View.VISIBLE
                    binding.buttonLeft.text = "刷新"
                    binding.buttonLeft.setOnClickListener { viewModel.reset() }
                    binding.buttonRight.text = "开始"
                    binding.buttonRight.setOnClickListener { viewModel.resume() }
                    handler.removeCallbacks(updateTimeRunnable)
                    binding.timeTextView.text = formatTime(viewModel.getCurrentDisplayTime())
                }
            }
        }

        // Observe marks list to update RecyclerView
        viewModel.marksLiveData.observe(viewLifecycleOwner) { marks ->
            adapter.submitList(marks)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        handler.removeCallbacks(updateTimeRunnable)
        _binding = null
    }

    // Format time from milliseconds to MM:SS.HH
    private fun formatTime(millis: Long): String {
        val minutes = (millis / 60000).toInt()
        val seconds = ((millis / 1000) % 60).toInt()
        val hundredths = ((millis / 10) % 100).toInt()
        return String.format("%02d:%02d.%02d", minutes, seconds, hundredths)
    }
}